package org.thanos.simulator.page.topic;

import org.thanos.simulator.api.MQTTClientApi;
import org.thanos.simulator.enums.Qos;
import org.thanos.simulator.page.IndexPage;

import javax.swing.*;
import javax.swing.text.NumberFormatter;
import java.awt.*;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class TopicPage {

    private final JTextField topic;

    private final JComboBox<String> qos;

    public TopicPage(IndexPage indexPage) {
        // 创建 JFrame
        JFrame frame = new JFrame("添加Topic");
        frame.setLocation(GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint());
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setLayout(new GridBagLayout()); // 使用 GridBagLayout

        // 创建 GridBagConstraints
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(5, 5, 5, 5); // 设置组件之间的间距

        gbc.gridy++;
        frame.add(new JLabel("Topic:"), gbc); // 添加标签
        gbc.gridx++;
        topic = new JTextField();
        topic.setPreferredSize(new Dimension(150, 30)); // 设置尺寸为 150x30 像素
        frame.add(topic, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        frame.add(new JLabel("Qos:"), gbc); // 添加标签
        gbc.gridx++;
        List<String> options = Arrays.stream(Qos.values()).map(Qos::getDesc).collect(Collectors.toList());
        qos = new JComboBox<>(options.toArray(new String[]{}));
        qos.setPreferredSize(new Dimension(150, 30)); // 设置尺寸为 150x30 像素
        frame.add(qos, gbc);

        // 创建确认按钮
        gbc.gridx = 0;
        gbc.gridy++;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        JButton button = new JButton("确认");
        button.addActionListener(e -> {
            try {
                String topicValue = topic.getText();
                String qosText = Objects.requireNonNull(qos.getSelectedItem()).toString();
                MQTTClientApi.subscribe(topicValue, Qos.descOf(qosText).getId());
                JOptionPane.showMessageDialog(null, "订阅成功！");
                indexPage.reloadMenu();
                frame.dispose();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
                throw new RuntimeException(ex);
            }
        });
        frame.add(button, gbc);
        frame.pack(); // 自适应大小
        frame.setVisible(true);
    }
}
